#  -*- coding: utf-8 -*-

from strategy.stock_pool.base_stock_pool import BaseStockPool
from factor.factor_module import FactorModule
from data.data_module import DataModule
from util.stock_util import get_trading_dates,get_all_codes_date,get_diff_dates,calc_negative_diff_dates,multi_computer,get_all_codes_trading_date,get_code_name
from pandas import DataFrame,Series
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import scipy.signal as signal
import time
from sklearn import linear_model
import pickle
import os
from util.database import DB_CONN, base_code_path
from pymongo import UpdateOne,ASCENDING
from pathlib import Path

"""
人工复盘（2022-02-12：已废弃）：
1，读取人工复盘的数据，通过其中的基本信息去填补其他信息；
2，补充完成后，存入数据库，并回填excel；
3，在visual模块去展示部分数据
4，定期去更新之前一些字段
"""

class ManualStockPool(BaseStockPool):

    def read_basic_info(self):
        self.file = Path(f"{base_code_path}/ManualStockPool.xlsx")

        data_df = pd.read_excel(self.file, sheencoding="gb2312", dtype=object)
        change_col = {
            "发现时间":'find_date',
            "停止跟踪时间":'stop_tracking_date',
            "代码":'code',
            "名称":'name',
            "发现日涨幅":'raise_ratio_find_date',
            "逻辑类型":'logic',
            "RS":'RS',
            "量比":'vol_ratio',
            "市值":'market_value',
            "成交量":'vol',
            "换手率":'turnover_rate',
            "形态学类型":'pattern_type',
            "形态学分析":'pattern_analyze',
            "量能分析":'vol_analyze',
            "涨幅位预期":'expect_price',
            "盈利预期分析":'expect_profit_analyze',
            "止损方法":'stop_loss_method',
            "止损预期分析":'stop_loss_analyze',
            "预期涨幅止损比":'expect_ratio_of_profit_2_loss',
            "预期卖出时间":'expect_sell_date',
            "真实走势分析":'live_trending_analyze',

        }
        data_df.rename(columns=change_col,inplace=True)
        data_df['find_date'] = data_df['find_date'].astype(str)
        data_df['code'] = data_df['code'].astype(str)

        print(data_df.head())

        return data_df

    def fill_data_df(self,data_df):
        return

    def write_manual_info_2_db(self,data_df):

        update_requests = list()
        collection = DB_CONN['trading_data']
        # 建立code+date的索引，提高save_data时写入数据的查询速度
        collection.create_index([('date', 1)])
        for index, row in data_df.iterrows():
            update_requests.append(
                UpdateOne(
                    {'index': index},
                    {'$set': dict(row)},
                    upsert=True)
            )
        # print(update_requests)
        # 批量写入，提高访问效率
        if len(update_requests) > 0:
            start_time = time.time()
            update_result = collection.bulk_write(update_requests, ordered=False)
            end_time = time.time()
            print('保存交易数据到数据集：%s，插入：%4d条, 更新：%4d条,耗时：%.3f 秒' %
                  (collection.name, update_result.upserted_count, update_result.modified_count,
                   (end_time - start_time)),
                  flush=True)

        return

    def write_back_2_file(self,data_df):
        return

    def get_option_stocks(self):
        #step1 从excel读取数据，并建立基础的data_df格式
        data_df = self.read_basic_info()

        #step2 填充data_df
        self.fill_data_df(data_df)
        #step3 写入数据库
        #self.write_manual_info_2_db(data_df)
        #step4 写回文件
        self.write_back_2_file(data_df)

        return

if __name__ == '__main__':
    pd.set_option('display.width', 130)
    pd.set_option('display.max_columns', 130)
    pd.set_option('display.max_colwidth', 130)

    mp = ManualStockPool(strategy_name="Manual", begin_date="2014-01-01",end_date="2019-06-18",interval=1)
    mp.get_option_stocks()

